package com.kye.express.business.welfare_integral;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.IView;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.integral.IntegralItemListResultDataBean;
import com.kye.model.bean.integral.IntegralItemType;
import com.kye.model.bean.integral.request.RequestIntegralItemList;
import com.kye.model.bean.user.User;
import com.kye.model.datasource.IntegralDataSource;

import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 18/12/2017
 * @updated : 18/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public interface IntegralItemListConstract {

    interface IntegralItemListView extends IView {

        void onUser(User user);

        void refreshInitSuccess(IntegralItemListResultDataBean integralItemListResultDataBean);

        void refreshInitNetFailed(String msg);

        void refreshInitServerFailed(String message);

        void enableLoadmore();

        void disableLoadmore();

        void refreshSuccess(IntegralItemListResultDataBean integralItemListResultDataBean);

        void refreshNetFailed(String msg);

        void refreshServerFailed(String message);

        void loadmoreSuccess(IntegralItemListResultDataBean integralItemListResultDataBean);

        void loadmoreNetFailed(String msg);

        void loadmoreServerFailed(String message);

    }

    class IntegralItemListPresenter extends BasePresenter<IntegralItemListView> {

        private IntegralDataSource integralDataSource;
        private PageInfo pageInfo;

        public IntegralItemListPresenter() {
            integralDataSource = new IntegralDataSource();
            pageInfo = PageInfo.newInstance();
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (savedInstanceState != null) {
                pageInfo = savedInstanceState.getParcelable(PageInfo.class.getSimpleName());
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            outState.putParcelable(PageInfo.class.getSimpleName(), pageInfo);
            super.onSaveInstanceState(outState);
        }

        @Override
        public void bind(IntegralItemListView view) {
            super.bind(view);
            UserSession.getInstance()
                    .getUserForRx()
                    .compose(getView().bindToLifecycleDestroy())
                    .subscribe(new Consumer<User>() {
                        @Override
                        public void accept(User user) throws Exception {
                            getView().onUser(user);
                        }
                    });
        }

        /**
         * 首次进入刷新
         * @param userInfo
         * @param integralTime
         * @param integralItemType
         */
        public void refreshInit(User userInfo, String integralTime, IntegralItemType integralItemType) {
            Single.just(new RequestIntegralItemList())
                    .doOnSuccess(new Consumer<RequestIntegralItemList>() {
                        @Override
                        public void accept(RequestIntegralItemList requestIntegralItemList) throws Exception {
                            requestIntegralItemList.setStartTime(integralTime);
                            requestIntegralItemList.setEndTime(integralTime);
                            // 类型（type=1为业务积分明细 type=2为拍照积分明细）
                            requestIntegralItemList.setIntegralType(integralItemType.getType());
                            requestIntegralItemList.setPageIndex(PageInfo.INDEX_DEFAULT);
                            requestIntegralItemList.setPageSize(PageInfo.SIZE_DEFAULT);
                            requestIntegralItemList.setPhone(userInfo.getPhone());
                        }
                    })
                    .flatMap(new Function<RequestIntegralItemList, SingleSource<OpenApiResult<IntegralItemListResultDataBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<IntegralItemListResultDataBean>> apply(RequestIntegralItemList requestIntegralItemList) throws Exception {
                            return integralDataSource.getIntegralDetailList(requestIntegralItemList)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<IntegralItemListResultDataBean>() {
                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<IntegralItemListResultDataBean> result, IntegralItemListResultDataBean integralItemListResultDataBean) {
                            pageInfo.resetPage();
                            getView().refreshInitSuccess(integralItemListResultDataBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<IntegralItemListResultDataBean> result, int code, String msg) {
                            getView().refreshInitServerFailed(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().refreshInitNetFailed(e.getMessage());
                        }

                        @Override
                        public void onLoaded() {

                        }
                    });
        }

        /**
         * 刷新
         * @param userInfo
         * @param integralTime
         * @param integralItemType
         */
        public void refresh(User userInfo, String integralTime, IntegralItemType integralItemType) {
            Single.just(new RequestIntegralItemList())
                    .doOnSuccess(new Consumer<RequestIntegralItemList>() {
                        @Override
                        public void accept(RequestIntegralItemList requestIntegralItemList) throws Exception {
                            requestIntegralItemList.setStartTime(integralTime);
                            requestIntegralItemList.setEndTime(integralTime);
                            // 类型（type=1为业务积分明细 type=2为拍照积分明细）
                            requestIntegralItemList.setIntegralType(integralItemType.getType());
                            requestIntegralItemList.setPageIndex(PageInfo.INDEX_DEFAULT);
                            requestIntegralItemList.setPageSize(PageInfo.SIZE_DEFAULT);
                            requestIntegralItemList.setPhone(userInfo.getPhone());
                        }
                    })
                    .flatMap(new Function<RequestIntegralItemList, SingleSource<OpenApiResult<IntegralItemListResultDataBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<IntegralItemListResultDataBean>> apply(RequestIntegralItemList requestIntegralItemList) throws Exception {
                            return integralDataSource.getIntegralDetailList(requestIntegralItemList)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<IntegralItemListResultDataBean>() {
                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<IntegralItemListResultDataBean> result, IntegralItemListResultDataBean integralItemListResultDataBean) {
                            pageInfo.resetPage();
                            getView().refreshSuccess(integralItemListResultDataBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<IntegralItemListResultDataBean> result, int code, String msg) {
                            getView().refreshServerFailed(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().refreshNetFailed(e.getMessage());
                        }

                        @Override
                        public void onLoaded() {

                        }
                    });
        }

        /**
         * 加载
         * @param userInfo
         * @param integralTime
         * @param integralItemType
         */
        public void loadmore(User userInfo, String integralTime, IntegralItemType integralItemType) {
            Single.just(new RequestIntegralItemList())
                    .doOnSuccess(new Consumer<RequestIntegralItemList>() {
                        @Override
                        public void accept(RequestIntegralItemList requestIntegralItemList) throws Exception {
                            requestIntegralItemList.setStartTime(integralTime);
                            requestIntegralItemList.setEndTime(integralTime);
                            // 类型（type=1为业务积分明细 type=2为拍照积分明细）
                            requestIntegralItemList.setIntegralType(integralItemType.getType());
                            requestIntegralItemList.setPageIndex(pageInfo.getPageIndex() + 1);
                            requestIntegralItemList.setPageSize(pageInfo.getPageSize());
                            requestIntegralItemList.setPhone(userInfo.getPhone());
                        }
                    })
                    .flatMap(new Function<RequestIntegralItemList, SingleSource<OpenApiResult<IntegralItemListResultDataBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<IntegralItemListResultDataBean>> apply(RequestIntegralItemList requestIntegralItemList) throws Exception {
                            return integralDataSource.getIntegralDetailList(requestIntegralItemList)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<IntegralItemListResultDataBean>() {
                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<IntegralItemListResultDataBean> result, IntegralItemListResultDataBean integralItemListResultDataBean) {
                            pageInfo.increasePage();
                            getView().loadmoreSuccess(integralItemListResultDataBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<IntegralItemListResultDataBean> result, int code, String msg) {
                            getView().loadmoreNetFailed(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().loadmoreServerFailed(e.getMessage());
                        }

                        @Override
                        public void onLoaded() {

                        }
                    });
        }

        public PageInfo getPageInfo() {
            return pageInfo;
        }
    }
}
